/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 * 模拟抢车:现在有三个车位，6辆车进行抢车位
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        //三个车位
        Semaphore semaphore = new Semaphore(3);
        //得到cpu核心数
        System.out.println(Runtime.getRuntime().availableProcessors());

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); //得到车位
                    System.out.println(Thread.currentThread().getName() + "得到车位");
                    //待了2s后离开，其他人开始抢车位
                    TimeUnit.SECONDS.sleep(2);
                    semaphore.release(); //释放
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }

}
